package com.creaylei.stock.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author zhang lei
 * @Date 2022-03-13 20:25
 */
@Slf4j
public class ExcelUtil {
    /**
     * excel   导出
     *
     * @param list      导出的数据
     * @param sheetName sheetName
     * @param pojoClass pojo类型
     * @param fileName  文件名称
     * @param response
     */
    public static void exportExcel(List<?> list, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
        //导出基本采用ExportParams 这个对象，进行参数配置；
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(sheetName);
        exportParams.setType(ExcelType.XSSF);//配置导出excel版本格式  ExcelType.XSSF后缀名为.xlsx ExcelType.HSSF后缀名为.xls
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder
                    .encode(fileName + ".xlsx", "UTF-8"));//这里根据上面ExcelType.XSSF配置来配，如果是 ExcelType.XSSF 对应 .xlsx ExcelType.HSSF对应.xls
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("error {}", e.getMessage());
            throw new IOException(e.getMessage());
        }
    }
}
